package dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import bean.Customer;
import bean.Fund;
import bean.Position;
import bean.UserBean;

public class PositionDAO extends DAO<UserBean> {
	
	public PositionDAO(SessionFactory factory) {
		super(factory);
	}
	
	public void createPosition(Customer c, Fund f, long amount) {
		if (c == null) throw new HibernateException("Customer does not exist.");
		if (f == null) throw new HibernateException("Fund does not exist.");
		
		Transaction tx = null;
		Session session = null;
		try {				
			session = this.getSession();
			tx = session.beginTransaction();
			
			Position p = new Position();
			p.setCustomer(c);
			p.setFund(f);
			p.setShares(amount);
			
			session.save(p);
			
			tx.commit();
		} finally {
			if (tx != null)	tx.rollback();
			if(session != null)	session.close();
		}
	}
	
	public Customer getCustomerByUsername(String username){
		//String idString = String.valueOf(id);
	
		List customers = this.getByAttribute("username", username, Customer.class);
		if(customers != null && customers.size()>0)
		{
			Customer customer = (Customer)customers.get(0);
			return customer;
		}
		return null;
	}
	
	public List<Position> getPositionByCusId(String customerId){
		List<Position> positions = this.getByAttribute("customer.id", customerId, Position.class);
		return positions;
	}
	
	public Position getPositionByKey(Customer c, Fund f,Session session) {
		
		Query q = session.createQuery("from Position p where p.customer.id = " + c.getId() + "and p.fund.id = " + f.getId());
		List<Position> list = q.list();
		if (list == null || list.size() == 0) return null;
		return list.get(0);
	}
	
	public void changeShare(Position p, long change) {
		if (p == null) return;
		
		Transaction tx = null;
		Session session = null;
		try {				
			session = this.getSession();
			tx = session.beginTransaction();
			
			p.setShares(p.getShares() + change);
			session.update(p);
			
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			if(session != null)	session.close();
		}
	}
	
	public String[] getPositionByCusIdByFundId(String customerId){
		List<Position> positions = this.getByAttribute("customer.id", customerId, Position.class);
		String[] fundPosition = new String[positions.size()];
		int i =0;
		for(Position p : positions)
		{
			fundPosition[i] = ""+p.getShares();
			i++;
		}
		
		return fundPosition;
	}
}